﻿using Longbow.GitHubAuth;
using Longbow.OAuth;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Configuration;
using System;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// GitHub 授权认证服务扩展类
    /// </summary>
    public static class GitHubExtensions
    {
        /// <summary>
        /// 添加 GitHub 认证授权服务
        /// </summary>
        /// <param name="builder">认证实例</param>
        /// <param name="configureOptions">GitHubAuthenticationOptions 权限配置项回调方法</param>
        /// <returns>AuthenticationBuilder 实例</returns>
        public static AuthenticationBuilder AddGitHub(this AuthenticationBuilder builder, Action<GitHubOptions> configureOptions = null) => builder.AddGitHub(GitHubDefaults.AuthenticationScheme, GitHubDefaults.DisplayName, configureOptions);

        /// <summary>
        /// 添加 GitHub 认证授权服务
        /// </summary>
        /// <param name="builder">认证实例</param>
        /// <param name="authenticationScheme">GitHub 认证架构名称 默认值为 GitHub</param>
        /// <param name="configureOptions">GitHubAuthenticationOptions 权限配置项回调方法</param>
        /// <returns>AuthenticationBuilder 实例</returns>
        public static AuthenticationBuilder AddGitHub(this AuthenticationBuilder builder, string authenticationScheme, Action<GitHubOptions> configureOptions = null) => builder.AddGitHub(authenticationScheme, GitHubDefaults.DisplayName, configureOptions);

        /// <summary>
        /// 添加 GitHub 认证授权服务
        /// </summary>
        /// <param name="builder">认证实例</param>
        /// <param name="authenticationScheme">GitHub 认证架构名称 默认值为 GitHub</param>
        /// <param name="displayName">GitHub 显示名称 默认值为 GitHub</param>
        /// <param name="configureOptions">GitHubAuthenticationOptions 权限配置项回调方法</param>
        /// <returns>AuthenticationBuilder 实例</returns>
        public static AuthenticationBuilder AddGitHub(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action<GitHubOptions> configureOptions = null)
        {
            var config = builder.Services.BuildServiceProvider().GetRequiredService<IConfiguration>();
            builder.Services.Configure<GitHubOptions>(authenticationScheme, config.GetSection(nameof(GitHubOptions)));
            return OAuthExtensions.AddOAuth<GitHubOptions, LgbOAuthHandler<GitHubOptions>>(builder, authenticationScheme, displayName, configureOptions);
        }
    }
}
